// 创建auth中间件 middleware/auth.js
const { verifyToken } = require('../utils/jwt');

module.exports = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
      return res.status(401).json({ code: 10001, message: "未提供Token" });
    }
    
    const token = authHeader.split(' ')[1];

    if (!token) {
      return res.status(401).json({ code: 10002, message: "Token格式错误，未提供Token!" });
    }
    console.log("请求token:",token);
    // 验证Token
    const decoded = verifyToken(token);
    console.log("验证token:",decoded);
    // 检查Token类型
    if (decoded.type !== 'access') {
      return res.status(401).json({ code: 10003, message: "非Access Token" });
    }
    
    // 附加用户信息到请求对象
    req.user = { id: decoded.userId };
    next();
  } catch (error) {
    return res.status(401).json({ 
      code: 10004, 
      message: error.message || "Token验证失败" 
    });
  }
};